package com.xinyu126.net_trace.share

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.tooling.preview.Preview
import com.xinyu126.net_trace.share.ui.theme.MagicalLocationTheme
import com.magical.location.model.Client
import com.magical.location.LocationDatabaseManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.MainScope
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.TextStyle
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.TextField
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color

import com.xinyu126.net_trace.Util

interface ClientListener {
    fun onClientAdded()

    fun addClient(clientId: String)

    fun getClients(): MutableList<Client>

    fun deleteClient(clientId: String)

    fun updateClient(client: Client)

    fun getMyClientId(): MutableState<String>
}

class ClientListenerImpl(context: Context) : ClientListener {
    private val database = LocationDatabaseManager(context)
    private val clients = mutableListOf<Client>()

    private var myClientId: MutableState<String> = mutableStateOf("")
    
    override fun onClientAdded() {
        var newClients  = database.getClients()
        if (newClients.isNotEmpty()) {
            clients.clear()
            clients.addAll(newClients)
        }
    }

    override fun addClient(clientId: String) {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                database.insertClient(clientId)
                onClientAdded()
            }
        }
    }

    override fun getClients(): MutableList<Client> {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                var newClients  = database.getClients()
                if (newClients.isNotEmpty()) {
                    clients.clear()
                    clients.addAll(newClients)
                }
            }
        }
        return clients
    }

    override fun deleteClient(clientId: String) {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                database.deleteClient(clientId)
                onClientAdded()
            }
        }
    }

    override fun updateClient(client: Client) {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                database.updateClient(client)
                onClientAdded()
            }
        }
    }

    override fun getMyClientId(): MutableState<String> {
        MainScope().launch {
            withContext(Dispatchers.IO) {
                var traceClient = database.getDAO().getSyncTrace()
                if (traceClient == null) {
                    traceClient = Util.newTraceClient()
                    database.getDAO().insertSyncTrace(traceClient)
                }
                var cid = traceClient.clientId
                myClientId.value = cid
            }
        }
        return myClientId
    }
}
class TestListener : ClientListener {
    override fun onClientAdded() {
        println("onClientAdded")
    }

    override fun addClient(clientId: String) {
        println("addClient: $clientId")
    }

    override fun updateClient(client: Client) {
        println("updateClient: $client")
    }

    override fun getMyClientId(): MutableState<String> {
        return mutableStateOf("aaa-gg-cc-adaf-dd")
    }

    override fun getClients(): MutableList<Client> {
        var clients = mutableListOf<Client>()
        var client = Client()
        client.clientId = "132-1212-443-1212312-345345345"
        client.client_name = "1"
        clients.add(client)
        client = Client()
        client.clientId = "233-232-4343-dfadsf"
        client.client_name = "23fadsf"
        clients.add(client)
        client = Client()
        client.clientId = "333-232-4343-dfadsf"
        client.client_name = "3"
        clients.add(client)
        return clients
    }

    override fun deleteClient(clientId: String) {
        println("deleteClient: $clientId")
    }
}

class ShareActivity : ComponentActivity() {

    private lateinit var clientListener: ClientListener


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        clientListener = ClientListenerImpl(this)
        setContent {
            MagicalLocationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    CreateView(
                        clientListener = clientListener,
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }


}

@Composable
fun CreateView(clientListener: ClientListener, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    var shareId = clientListener.getMyClientId()
    
    // 颜色适配主题
    val textColorMain = MaterialTheme.colorScheme.onSurface.copy(alpha = 1f)
    val textColorGray = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)

    Column(modifier = modifier.padding(16.dp)) {

        // 第一行：分享ID
        Row(modifier = Modifier.fillMaxWidth()) {
            // 字号 12
            TextField(
                value = shareId.value,
                readOnly = true,
                leadingIcon = {Text("我:",style=TextStyle(fontSize = 12.sp))},
                singleLine = true,
                onValueChange = { shareId.value = it },
                modifier = Modifier.padding(0.dp).fillMaxWidth(),
                colors = TextFieldDefaults.colors(
                    unfocusedContainerColor  = Color.Transparent
                ),
                textStyle = TextStyle(fontSize = 12.sp)
            )
        }
        Row(modifier = Modifier.fillMaxWidth()) {
            //靠右
            Spacer(modifier = Modifier.weight(1f))
            Button(
                onClick = {
                    // 把ShareText 复制到剪切板
                    val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val clipData = ClipData.newPlainText("share_id", shareId.value)
                    clipboardManager.setPrimaryClip(clipData)
                    Toast.makeText(context, "分享ID已复制", Toast.LENGTH_SHORT).show()
                }
            ) {
                Text("复制")
            }
        }

        Spacer(modifier = Modifier.height(12.dp))
        var clientIdText by remember { mutableStateOf("") }
        // 第二行：添加Client ID
        Row(modifier = Modifier.fillMaxWidth()) {
            Text("添加需要关注的 Client ID", color = textColorGray, fontSize = 12.sp)
        }
        Row(modifier = Modifier.fillMaxWidth()) {
            TextField(
                value = clientIdText,
                onValueChange = { clientIdText = it },
                modifier = Modifier.weight(1f),
                placeholder = { Text("请输入Client Id") },
                singleLine = true
            )
        }
        Row(modifier = Modifier.fillMaxWidth()) {
            // 靠右
            Spacer(modifier = Modifier.weight(1f))
            Button(
                onClick = { 
                    if (clientIdText.isNotEmpty()) {
                        clientListener.addClient(clientIdText)

                        Toast.makeText(context, "Client ID已保存", Toast.LENGTH_SHORT).show()
                        clientIdText = ""
                    } else {
                        Toast.makeText(context, "请输入Client ID", Toast.LENGTH_SHORT).show()
                    }
                }
            ) {
                Text("添加")
            }
        }

        // 第三行：从本地获取Client ID
        Column(modifier = Modifier.padding(16.dp)) {


            // 循环
            for (client in clientListener.getClients()) {

                Row(modifier = Modifier.fillMaxWidth().padding(2.dp)) {
                    var name = client.client_name
                    if (name.isEmpty()) {
                        name = "无名"
                    }
                    var showDialog by remember { mutableStateOf(false) }
                    var newName by remember { mutableStateOf(name) }
                   
                    Text(name, color = textColorMain, fontSize = 16.sp, modifier = Modifier.clickable {
                        showDialog = true
                    })
                    
                    if (showDialog) {
                        AlertDialog(
                            onDismissRequest = { showDialog = false },
                            title = { Text("输入名字,最多2字") },
                            text = {
                                TextField(
                                    value = newName,
                                    onValueChange = { newName = it }
                                )
                            },
                            confirmButton = {
                                TextButton(
                                    onClick = {
                                        if (newName.length > 2) {
                                            newName = newName.substring(0, 2)
                                        }
                                        client.client_name = newName
                                        clientListener.updateClient(client)
                                        showDialog = false
                                    }
                                ) {
                                    Text("确定")
                                }
                            },
                            dismissButton = {
                                TextButton(onClick = { showDialog = false }) {
                                    Text("取消")
                                }
                            }
                        )
                    }
                    
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(client.clientId, color = textColorGray, fontSize = 12.sp, modifier=Modifier.weight(1f))
                    // 删除按钮,迷你,红色背景
                    IconButton (
                        onClick = {
                            clientListener.deleteClient(client.clientId)
                        },modifier=modifier.padding(0.dp)
                    ) {
                        //Icon(painterResource(R.dra))
                        // delete Icon
                        Icon(Icons.Default.Delete, contentDescription = "删除", tint = Color.Red,modifier=Modifier.offset(x=0.dp))
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 打开地图按钮
        Button(
            onClick = {
                // 打开地图
                val intent = Intent(context, MapActivity::class.java)
                intent.putExtra("myId",shareId.value)
                context.startActivity(intent)
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("打开地图")
        }
    }
}

@Preview(name = "Light Mode", showBackground = true)
@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_YES,
    showBackground = false,
    name = "Dark Mode"
)
@Composable
fun GreetingPreview() {
    MagicalLocationTheme {
        val clientListener = TestListener()
        CreateView(clientListener)
    }
}
